using System;
using System.Data.Linq;
using System.Linq;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadGifts();
        }

    }

    private void LoadGifts()
    {
        using (GiftsDataContext ctx = new GiftsDataContext())
        {
            var gifts = ctx.Gifts.OrderBy(a => a.GiftName);
            GiftsListView.DataSource = gifts;
            GiftsListView.DataBind();
        }
    }
    protected void GiftsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            Gift boundGift = (e.Item as ListViewDataItem).DataItem as Gift;
            WebControl reserveButton = e.Item.FindControl("ReserveButton") as WebControl;
            TextBox ReservedByTextBox = e.Item.FindControl("ReservedByTextBox") as TextBox;
            HyperLink LinkUrlLink = e.Item.FindControl("LinkUrlLink") as HyperLink;
            if (!string.IsNullOrEmpty(boundGift.LinkUrl))
            {
                LinkUrlLink.Visible = true;
            }
            if (boundGift.IsReserved == true || boundGift.IsReserved == null)
            {
                reserveButton.Visible = false;
                ReservedByTextBox.Visible = false;
            }
            else
            {
                reserveButton.Visible = true;
                ReservedByTextBox.Visible = true;
            }
        }
    }

    protected void GiftsListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
    {

        ListViewDataItem item = GiftsListView.Items[e.NewSelectedIndex];
        if (item.ItemType == ListViewItemType.DataItem)
        {
            LinkButton ReserveButton = item.FindControl("ReserveButton") as LinkButton;
            Guid IDForUpdate = new Guid(ReserveButton.CommandArgument);
            using (GiftsDataContext ctx = new GiftsDataContext())
            {
                Gift giftToUpdate = ctx.Gifts.Single(a => a.ID == IDForUpdate);
                TextBox ReservedByTextBox = item.FindControl("ReservedByTextBox") as TextBox;
                
                giftToUpdate.ReservedBy = ReservedByTextBox.Text;
                giftToUpdate.IsReserved = true;
                if (giftToUpdate.ReservedBy.Length>3)
                {
                    ctx.SubmitChanges();    
                }
            }
            LoadGifts();
        }

    }
}